
package com.ruoyi.system.listener;

import com.ruoyi.system.config.RabbitMQConfig;
import com.ruoyi.system.domain.message.ScheduleNotificationMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 排班通知消息监听器
 *
 * @author ruoyi
 */
@Slf4j
@Component
public class ScheduleNotificationListener {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 处理排班通知消息
     *
     * @param message 原始消息对象
     */
    @RabbitListener(queues = RabbitMQConfig.SCHEDULE_NOTIFICATION_QUEUE)
    public void handleScheduleNotification(Message message) {
        try {
            // 获取消息体字节数组
            byte[] messageBody = message.getBody();
            String messageStr = new String(messageBody, java.nio.charset.StandardCharsets.UTF_8);
            log.info("收到排班通知消息: {}", messageStr);

            // 清理消息格式（移除多余的引号）
            String cleanedMessage = messageStr;
            if (messageStr.startsWith("\"") && messageStr.endsWith("\"")) {
                cleanedMessage = messageStr.substring(1, messageStr.length() - 1);
                // 处理转义字符
                cleanedMessage = cleanedMessage.replace("\\\"", "\"");
            }

            log.info("清理后的消息: {}", cleanedMessage);

            // 手动解析JSON消息
            com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
            ScheduleNotificationMessage notification = objectMapper.readValue(cleanedMessage, ScheduleNotificationMessage.class);

            log.info("解析后的通知: 警员={}, 类型={}, 内容={}",
                    notification.getOfficerName(),
                    notification.getMessageType(),
                    notification.getContent());

            // 处理通知逻辑
            processNotification(notification);

        } catch (Exception e) {
            log.error("处理排班通知失败: {}", new String(message.getBody(), java.nio.charset.StandardCharsets.UTF_8), e);
        }
    }

    /**
     * 处理通知的具体业务逻辑
     *
     * @param notification 通知消息
     */
    private void processNotification(ScheduleNotificationMessage notification) {
        // 这里可以添加具体的处理逻辑：
        // 1. 保存通知到数据库
        // 2. 通过SSE推送到前端
        // 3. 发送短信或邮件通知
        // 4. 记录操作日志

        log.info("处理排班通知 - 警员ID: {}, 消息类型: {}, 排班日期: {}",
                notification.getOfficerId(),
                notification.getMessageType(),
                notification.getScheduleDate());

        // 通过RestTemplate直接调用SSE接口
        try {
            log.info("开始SSE推送 - 警员ID: {}, 消息: {}", notification.getOfficerId(), notification.getContent());

            // 创建简单的通知数据
            java.util.Map<String, Object> notificationData = new java.util.HashMap<>();
            notificationData.put("title", notification.getTitle());
            notificationData.put("content", notification.getContent());
            notificationData.put("messageType", notification.getMessageType());
            notificationData.put("officerName", notification.getOfficerName());
            notificationData.put("shiftName", notification.getShiftName());
            notificationData.put("scheduleDate", notification.getScheduleDate());
            notificationData.put("createTime", notification.getCreateTime() != null ? notification.getCreateTime().getTime() : System.currentTimeMillis());

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 创建请求实体
            HttpEntity<java.util.Map<String, Object>> request = new HttpEntity<>(notificationData, headers);

            // 调用SSE接口
            String sseUrl = "http://localhost:8080/sse/sendScheduleNotification/" + notification.getOfficerId();
            String result = restTemplate.postForObject(sseUrl, request, String.class);
            log.info("SSE推送结果: {}", result);

        } catch (Exception e) {
            log.error("SSE推送失败", e);
        }
    }
}
